package com.mondo.financialwallet.presentation.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.annotation.StringRes;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.common.ui.AbsNetworkStateActivity;
import com.example.common.zxing.encoding.EncodingHandler;
import com.mondo.financialwallet.R;
import com.mondo.financialwallet.data.DataRepository;
import com.mondo.financialwallet.data.entity.GoogleValidatorEntity;
import com.mondo.financialwallet.presentation.utils.ActivityTitleBarHelper;
import com.mondo.financialwallet.presentation.utils.AndroidUtils;
import com.mondo.financialwallet.presentation.utils.LocalConfigStorage;
import com.mondo.financialwallet.presentation.utils.Toasts;

import butterknife.Bind;

/**
 * 修改或绑定谷歌验证器
 */
public class BindAndEditGoogleValidatorActivity extends AbsNetworkStateActivity {

    private static final String EXTRA_PAGE_TYPE = "PAGE_TYPE", BIND_PAGE_TYPE = "BIND",
            EDIT_PAGE_TYPE = "EDIT";

    public static void launchBind(Context context) {
        context.startActivity(
                new Intent(context, BindAndEditGoogleValidatorActivity.class)
                        .putExtra(EXTRA_PAGE_TYPE, BIND_PAGE_TYPE)
        );
    }

    public static void launchEdit(Context context) {
        context.startActivity(
                new Intent(context, BindAndEditGoogleValidatorActivity.class)
                        .putExtra(EXTRA_PAGE_TYPE, EDIT_PAGE_TYPE)
        );
    }

    @Bind(R.id.code_edit) EditText mCodeEditText;
    @Bind(R.id.sure_button) Button mSureButton;
    @Bind(R.id.copy_code_image) View mCopyCodeImage;
    @Bind(R.id.google_validator_code_text) TextView mCodeTextView;
    @Bind(R.id.google_validator_code_image) ImageView mCodeImageView;

    private @StringRes int mTitleStringRes;

    @Override
    protected int getBackgroundColor() {
        return Color.WHITE;
    }

    @Override
    protected void setStatusBar() {
        ActivityTitleBarHelper.setWhiteDarkColorStatus(this);
    }

    @Override
    protected int getLayoutID() {
        String pageType = getIntent().getStringExtra(EXTRA_PAGE_TYPE);
        if (BIND_PAGE_TYPE.equals(pageType)) {
            mTitleStringRes = R.string.title_bind_google_validator;
            return R.layout.activity_bind_google_validator;
        }

        mTitleStringRes = R.string.title_edit_google_validator;
        return R.layout.activity_edit_google_validator;
    }

    @Override
    protected void initActions() {
        ActivityTitleBarHelper.init(this, mTitleStringRes);

        // 请求验证器信息
        requestGoogleValidatorInfo();

        // 绑定验证器
        mSureButton.setOnClickListener(v -> bindGoogleValidator());
    }

    private void bindGoogleValidator() {
        String code = mCodeEditText.getText().toString();
        if (TextUtils.isEmpty(code)) {
            Toasts.warning(R.string.message_please_enter_google_validator_code);
            return;
        }

        DataRepository.get().bindGoogleValidator(code, result -> {
            if (result.isSuccess()) {
                Toasts.success(R.string.message_bind_success);
                LocalConfigStorage.get().bindGoogleValidator(true);
                finish();
            } else {
                Toasts.failure(result.getMsg());
            }
        });
    }

    private void requestGoogleValidatorInfo() {
        loadingNetwork();

        DataRepository.get().googleValidator(result -> {
            if (result.isSuccess()) {
                successNetwork();
                GoogleValidatorEntity.DataBean data = result.getData();
                mCodeTextView.setText(data.getGoogle_code());
                createRqCodeImage(data.getGoogle_code());

                mCopyCodeImage.setOnClickListener(v -> {
                    AndroidUtils.copyToChipBoard(v.getContext(), data.getGoogle_code());
                    Toasts.success(R.string.message_copy_success);
                });
            } else {
                //errorNetwork(result.getMsg());
                successNetwork();
            }
        });
    }

    // 'otpauth://totp/'+username+'?secret='+ this.google_key+'&issuer=www.superid.in
    private void createRqCodeImage(String address) {
        try {
            Bitmap addressBitmap = EncodingHandler.createQRCode(
                    "otpauth://totp/"
                            + getString(R.string.app_name)
                            + "?secret="
                            + address
                            + "&issuer=www.superid.in",
                    getResources().getDimensionPixelOffset(R.dimen.rq_code_image_size));
            mCodeImageView.setImageBitmap(addressBitmap);
            mCodeImageView.setBackgroundColor(Color.WHITE);
        } catch (Exception e) {
            Toasts.failure(e.getMessage());
            finish();
        }
    }

    @Override
    public void onAnewRequest() {
        requestGoogleValidatorInfo();
    }
}
